package com.wushijia.highconcurrency.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo1 {

  static class MyRecursiveTask extends RecursiveTask<Integer> {

    private Integer beginPosition;
    private Integer endPosition;

    MyRecursiveTask(Integer beginPosition, Integer endPosition) {
      this.beginPosition = beginPosition;
      this.endPosition = endPosition;
    }

    @Override
    protected Integer compute() {
      Integer sumValue = 0;
      if ((endPosition - beginPosition) != 0) {
        Integer midPosition = (endPosition + beginPosition) / 2;
        MyRecursiveTask leftRecursiveTask = new MyRecursiveTask(beginPosition, midPosition);
        MyRecursiveTask rightRecursiveTask = new MyRecursiveTask(midPosition + 1, endPosition);
        invokeAll(leftRecursiveTask, rightRecursiveTask);
        Integer leftValue = leftRecursiveTask.join();
        Integer rightValue = rightRecursiveTask.join();
        return leftValue + rightValue;
      } else {
        return endPosition;
      }
    }
  }

  public static void main(String[] args) {
    MyRecursiveTask myRecursiveTask = new MyRecursiveTask(1, 11);
    ForkJoinPool forkJoinPool = new ForkJoinPool();
    forkJoinPool.submit(myRecursiveTask);
    try {
      System.out.println(myRecursiveTask.get());
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
  }
}
